<?php

namespace app\admin\controller;

use app\admin\model\Collect;
use app\admin\model\Device;
use app\common\controller\Backend;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Summary extends Backend
{

    /**
     * Collect模型对象
     * @var \app\admin\model\Collect
     */
    protected $model = null;
    protected $dataLimit = 'auth';

    public function _initialize()
    {
        parent::_initialize();

        $day = 6;
        $startdate = date('Y-m-d 00:00:00', strtotime("-$day day"));
        $enddate = date('Y-m-d 23:59:59');
        $this->assignconfig('date', $startdate . ' - '. $enddate);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 养号
     */
    public function index()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            // 分页
            $offset = max(0, $this->request->get("offset/d", 0));
            $limit = max(0, $this->request->get("limit/d", 0));
            $limit = $limit ?: 999999;
            //新增自动计算页码
            $page = $limit ? intval($offset / $limit) + 1 : 1;
            if ($this->request->has("page")) {
                $page = max(0, $this->request->get("page/d", 1));
            }
            $this->request->get([config('paginate.var_page') => $page]);

            // 默认取当前管理员下的
            $admin_ids = $this->auth->getChildrenAdminIds(true);

            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '','trim'), true);
            if(isset($filter['groupIds'])){
                $groupIds = $this->auth->getByGroupIds($filter['groupIds']);
                $admin_ids = model('AuthGroupAccess')->where('group_id', 'in', $groupIds)->column('uid');
                unset($filter['groupIds'], $op['groupIds']);
                $where['admin_id'] = ['in', $admin_ids];

            }

            if(isset($filter['admin_id'])){
                $admin_id = [$filter['admin_id']];
                unset($filter['groupIds'], $op['groupIds']);
                $where['admin_id'] = ['in', $admin_id];
            }

            $this->request->get(['filter' => json_encode($filter, true)]);
            $this->request->get(['op' => json_encode($op, true)]);

            // 搜索
            $filter = json_decode($this->request->get("filter", ''), true);

            $where['type'] = $filter['type'] ?? 1;

            // dd($filter);

            // 设备号
            $deviceArr = Device::column('mobile_serial', 'id');

            // 负责人
            $admin = db('admin')->column('nickname',  'id');

            $fields = "date,admin_id,device_id,sum(play_num) play_num,sum(fans) fans,sum(volume) volume,sum(turnover) turnover,sum(amount) amount,sum(violent_num) violent_num";
            $list = Collect::field($fields)->group('date,admin_id,device_id');
            
            // 粉丝上涨下降
            $last = $list;

            if(isset($filter['date']) && $filter['date'] != ''){
                $list = $list->whereTime('date', 'between', explode(' - ', $filter['date']));
            }

            if(isset($filter['mobile_serial']) && $filter['mobile_serial'] != ''){
                $list = $list->where('device_id', array_flip($deviceArr)[$filter['mobile_serial']]);
            }

            if(isset($filter['nickname']) && $filter['nickname'] != ''){
                $nickname = $filter['nickname'];
                $adminArr = db('admin')->where('nickname', 'like', "%{$nickname}%")->column('id');
                $list = $list->where('admin_id', 'in', $adminArr);
            }

            $list = $list
                ->where($where)
                ->order('date desc')
                ->order('device_id asc')
                ->paginate($limit);

            // 粉丝上涨下降
            $last = $last->where($where)->select();
            $arr = [];
            $fans = 0;
            foreach ($last as $row) {
                $arr[$row['device_id'] . $row['date']] = $row['fans'];
                $fans += $row['fans'];
            }    
            foreach($list as $row){
                $row->mobile_serial = $deviceArr[$row->device_id] ?? '';
                $row->nickname = $admin[$row->admin_id] ?? '';

                $row->yestoday_date = date('Y-m-d', strtotime($row->date) - 86400);
                $row->yestoday_fans = isset($arr[$row->device_id . $row->yestoday_date]) 
                                ? $arr[$row->device_id . $row->yestoday_date]
                                : 0;
                $row->fans_diff = abs($row->fans - $row->yestoday_fans);
            }

            $extend = [
                'fans' => $fans
            ];
            $result = array("total" => $list->total(), "rows" => $list->items(), 'extend' => $extend);

            return json($result);
        }

        // $day = 6;
        // $startdate = date('Y-m-d 00:00:00', strtotime("-$day day"));
        // $enddate = date('Y-m-d 23:59:59');
        // $this->assignconfig('date', $startdate . ' - '. $enddate);
        return $this->view->fetch();
    }

    /**
     * 带货
     */
    public function home()
    {
        return $this->view->fetch('index');
    }

    /**
     * 中视频
     */
    public function violent()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            // 分页
            $offset = max(0, $this->request->get("offset/d", 0));
            $limit = max(0, $this->request->get("limit/d", 0));
            $limit = $limit ?: 999999;
            //新增自动计算页码
            $page = $limit ? intval($offset / $limit) + 1 : 1;
            if ($this->request->has("page")) {
                $page = max(0, $this->request->get("page/d", 1));
            }
            $this->request->get([config('paginate.var_page') => $page]);

            // 默认取当前管理员下的
            $admin_ids = $this->auth->getChildrenAdminIds(true);

            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '','trim'), true);
            if(isset($filter['groupIds'])){
                $groupIds = $this->auth->getByGroupIds($filter['groupIds']);
                $admin_ids = model('AuthGroupAccess')->where('group_id', 'in', $groupIds)->column('uid');
                unset($filter['groupIds'], $op['groupIds']);
            }
            $this->request->get(['filter' => json_encode($filter, true)]);
            $this->request->get(['op' => json_encode($op, true)]);

            // 搜索
            $filter = json_decode($this->request->get("filter", ''), true);

            $where['admin_id'] = ['in', $admin_ids];
            $where['type'] = $filter['type'] ?? 1;

            // dd($filter);

            // 设备号
            $deviceArr = Device::column('mobile_serial', 'id');

            // 负责人
            $admin = db('admin')->column('nickname',  'id');

            $fields = "date,admin_id,device_id,sum(play_num) play_num,sum(fans) fans,sum(volume) volume,sum(turnover) turnover,sum(amount) amount,sum(violent_num) violent_num";
            $list = Collect::field($fields)->group('date,admin_id,device_id');
            
            // 粉丝上涨下降
            $last = $list;

            if(isset($filter['date']) && $filter['date'] != ''){
                $list = $list->whereTime('date', 'between', explode(' - ', $filter['date']));
                $last = $last->whereTime('date', 'between', explode(' - ', $filter['date']));
            }

            if(isset($filter['mobile_serial']) && $filter['mobile_serial'] != ''){
                $list = $list->where('device_id', array_flip($deviceArr)[$filter['mobile_serial']]);
                $last = $last->where('device_id', array_flip($deviceArr)[$filter['mobile_serial']]);
            }

            if(isset($filter['nickname']) && $filter['nickname'] != ''){
                $nickname = $filter['nickname'];
                $adminArr = db('admin')->where('nickname', 'like', "%{$nickname}%")->column('id');
                $list = $list->where('admin_id', 'in', $adminArr);
                $last = $last->where('admin_id', 'in', $adminArr);
            }

            $list = $list
                ->where($where)
                ->order('date desc')
                ->order('device_id asc')
                ->paginate($limit);


            if(isset($filter['date']) && $filter['date'] != ''){
                $last = $last->whereTime('date', 'between', explode(' - ', $filter['date']));
            }

            if(isset($filter['mobile_serial']) && $filter['mobile_serial'] != ''){
                $last = $last->where('device_id', array_flip($deviceArr)[$filter['mobile_serial']]);
            }

            if(isset($filter['nickname']) && $filter['nickname'] != ''){
                $nickname = $filter['nickname'];
                $adminArr = db('admin')->where('nickname', 'like', "%{$nickname}%")->column('id');
                $last = $last->where('admin_id', 'in', $adminArr);
            }

            // 粉丝上涨下降
            $last = $last->where($where)->select();
            $arr = [];
            $amount = 0;
            foreach ($last as $row) {
                $arr[$row['device_id'] . $row['date']] = $row['fans'];
                $amount += $row['amount'];
            }    
            foreach($list as $row){
                $row->mobile_serial = $deviceArr[$row->device_id] ?? '';
                $row->nickname = $admin[$row->admin_id] ?? '';

                $row->yestoday_date = date('Y-m-d', strtotime($row->date) - 86400);
                $row->yestoday_fans = isset($arr[$row->device_id . $row->yestoday_date]) 
                                ? $arr[$row->device_id . $row->yestoday_date]
                                : 0;
                $row->fans_diff = abs($row->fans - $row->yestoday_fans);
            }
            $extend = [
                'amount' => sprintf('%.2f', $amount),
            ];
            $result = array("total" => $list->total(), "rows" => $list->items(), 'extend' => $extend);
            
            return json($result);
        }

        return $this->view->fetch('index');
    }
}